#!/usr/bin/env node

/**
 * UC系统异步架构启动脚本
 * 解决net::ERR_CONNECTION_RESET问题的完整方案
 *
 * 启动顺序：
 * 1. 初始化队列系统
 * 2. 启动AI推理Worker
 * 3. 启动Express服务器
 * 4. 启动监控和日志
 */

const express = require('express');
const cors = require('cors');
const path = require('path');
const fs = require('fs').promises;
const { spawn } = require('child_process');

// 导入配置和组件
const simpleQueueConfig = require('./src/config/simpleQueueConfig');
const simpleAiInferenceWorker = require('./src/workers/simpleAiInferenceWorker');
const db = require('./src/config/database');

// 系统配置
const PORT = process.env.PORT || 4000;
const NODE_ENV = process.env.NODE_ENV || 'development';

// 全局状态
let queueInitialized = false;
let workerStarted = false;
let server = null;
let workerProcess = null;

/**
 * 初始化队列系统
 */
async function initializeQueueSystem() {
  try {
    console.log('🔄 [1/4] 初始化队列系统...');

    const success = await simpleQueueConfig.initializeQueues();

    if (success) {
      queueInitialized = true;
      console.log('✅ [1/4] 队列系统初始化成功');

      // 获取队列统计
      const stats = await simpleQueueConfig.getQueueStats();
      console.log('📊 队列状态:', stats);
    } else {
      console.warn('⚠️ [1/4] 队列系统初始化失败，系统将以降级模式运行');
    }

    return success;

  } catch (error) {
    console.error('❌ [1/4] 队列系统初始化失败:', error);
    return false;
  }
}

/**
 * 启动AI推理Worker
 */
async function startAIInferenceWorker() {
  try {
    console.log('🔄 [2/4] 启动AI推理Worker...');

    if (queueInitialized) {
      // 如果队列可用，Worker会自动启动
      workerStarted = true;
      console.log('✅ [2/4] AI推理Worker已启动（队列模式）');
    } else {
      // 降级模式：启动独立的Worker进程
      console.log('⚠️ [2/4] 队列不可用，启动独立Worker进程...');

      workerProcess = spawn('node', [
        './src/workers/simpleAiInferenceWorker.js'
      ], {
        stdio: 'inherit',
        cwd: process.cwd()
      });

      workerProcess.on('error', (error) => {
        console.error('❌ AI Worker进程启动失败:', error);
      });

      workerProcess.on('exit', (code) => {
        console.log(`AI Worker进程退出，代码: ${code}`);
        workerStarted = false;
      });

      // 等待进程启动
      await new Promise(resolve => setTimeout(resolve, 2000));

      if (workerProcess && !workerProcess.killed) {
        workerStarted = true;
        console.log('✅ [2/4] AI推理Worker已启动（独立进程模式）');
      } else {
        throw new Error('Worker进程启动失败');
      }
    }

    return true;

  } catch (error) {
    console.error('❌ [2/4] AI推理Worker启动失败:', error);
    return false;
  }
}

/**
 * 创建Express应用
 */
function createExpressApp() {
  const app = express();

  // 中间件
  app.use(cors());
  app.use(express.json({ limit: '50mb' }));
  app.use(express.urlencoded({ extended: true, limit: '50mb' }));

  // 静态文件服务
  app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

  // 健康检查
  app.get('/health', (req, res) => {
    res.json({
      success: true,
      message: 'EndoSight-UC 异步架构版运行正常',
      data: {
        timestamp: new Date().toISOString(),
        version: '2.0.0-async',
        environment: NODE_ENV,
        queueInitialized,
        workerStarted,
        uptime: process.uptime()
      }
    });
  });

  // 队列状态检查
  app.get('/queue/status', async (req, res) => {
    try {
      if (!queueInitialized) {
        return res.json({
          success: false,
          message: '队列系统未初始化',
          data: null
        });
      }

      const stats = await simpleQueueConfig.getQueueStats();
      res.json({
        success: true,
        message: '获取队列状态成功',
        data: stats
      });

    } catch (error) {
      console.error('获取队列状态失败:', error);
      res.status(500).json({
        success: false,
        message: '获取队列状态失败',
        data: null
      });
    }
  });

  // 系统状态检查
  app.get('/system/status', async (req, res) => {
    try {
      // 检查数据库连接
      const dbTest = await db.query('SELECT 1 as test');

      // 检查队列状态
      let queueStats = null;
      if (queueInitialized) {
        queueStats = await simpleQueueConfig.getQueueStats();
      }

      res.json({
        success: true,
        message: '系统状态检查完成',
        data: {
          database: {
            status: 'connected',
            test: dbTest[0]?.test
          },
          queue: {
            initialized: queueInitialized,
            stats: queueStats
          },
          worker: {
            started: workerStarted,
            pid: workerProcess?.pid || 'embedded'
          },
          server: {
            port: PORT,
            uptime: process.uptime(),
            memory: process.memoryUsage(),
            node_version: process.version
          }
        }
      });

    } catch (error) {
      console.error('系统状态检查失败:', error);
      res.status(500).json({
        success: false,
        message: '系统状态检查失败',
        data: null
      });
    }
  });

  // 导入路由
  try {
    // 使用简化版控制器
    const simpleScoringController = require('./src/controllers/simpleScoringController');
    const authMiddleware = require('./src/middleware/auth');

    // 评分相关路由
    app.post('/api/scoring/submit', authMiddleware.authenticateToken, simpleScoringController.submitTask);
    app.post('/api/scoring/status', authMiddleware.authenticateToken, simpleScoringController.getTaskStatus);
    app.post('/api/scoring/list', authMiddleware.authenticateToken, simpleScoringController.getTaskList);
    app.post('/api/scoring/result', authMiddleware.authenticateToken, simpleScoringController.getTaskResult);
    app.get('/api/scoring/queue-stats', authMiddleware.authenticateToken, simpleScoringController.getQueueStats);

    // 兼容原有路由
    const authRoutes = require('./src/routes/auth');
    const doctorRoutes = require('./src/routes/doctors');

    app.use('/api', authRoutes);
    app.use('/api/doctors', doctorRoutes);

    console.log('✅ 路由加载完成');

  } catch (error) {
    console.error('❌ 路由加载失败:', error);
  }

  return app;
}

/**
 * 启动Express服务器
 */
async function startExpressServer() {
  try {
    console.log('🔄 [3/4] 启动Express服务器...');

    const app = createExpressApp();

    server = app.listen(PORT, '0.0.0.0', () => {
      console.log('✅ [3/4] Express服务器启动成功');
      console.log(`🌐 服务器地址: http://localhost:${PORT}`);
      console.log(`📊 健康检查: http://localhost:${PORT}/health`);
      console.log(`📈 队列状态: http://localhost:${PORT}/queue/status`);
      console.log(`🔍 系统状态: http://localhost:${PORT}/system/status`);
    });

    server.on('error', (error) => {
      if (error.code === 'EADDRINUSE') {
        console.error(`❌ 端口 ${PORT} 已被占用`);
      } else {
        console.error('❌ Express服务器启动失败:', error);
      }
      process.exit(1);
    });

    return true;

  } catch (error) {
    console.error('❌ [3/4] Express服务器启动失败:', error);
    return false;
  }
}

/**
 * 启动监控和日志
 */
async function startMonitoring() {
  try {
    console.log('🔄 [4/4] 启动监控和日志...');

    // 定期输出系统状态
    setInterval(async () => {
      try {
        const memUsage = process.memoryUsage();
        const uptime = process.uptime();

        console.log('📊 系统监控:', {
          uptime: `${Math.floor(uptime / 60)}m ${Math.floor(uptime % 60)}s`,
          memory: {
            rss: `${Math.round(memUsage.rss / 1024 / 1024)}MB`,
            heap: `${Math.round(memUsage.heapUsed / 1024 / 1024)}MB`
          },
          queue: queueInitialized ? 'active' : 'disabled',
          worker: workerStarted ? 'running' : 'stopped'
        });

        // 如果队列可用，输出队列统计
        if (queueInitialized) {
          const stats = await simpleQueueConfig.getQueueStats();
          if (stats.total > 0) {
            console.log('📈 队列统计:', stats);
          }
        }

      } catch (error) {
        console.error('监控数据获取失败:', error);
      }
    }, 30000); // 每30秒输出一次

    console.log('✅ [4/4] 监控和日志已启动');
    return true;

  } catch (error) {
    console.error('❌ [4/4] 监控和日志启动失败:', error);
    return false;
  }
}

/**
 * 优雅关闭
 */
async function gracefulShutdown(signal) {
  console.log(`\n🛑 收到${signal}信号，开始优雅关闭...`);

  try {
    // 1. 停止接受新请求
    if (server) {
      server.close();
      console.log('✅ Express服务器已关闭');
    }

    // 2. 关闭Worker进程
    if (workerProcess && !workerProcess.killed) {
      workerProcess.kill('SIGTERM');
      console.log('✅ AI Worker进程已关闭');
    }

    // 3. 关闭队列系统
    if (queueInitialized) {
      await simpleQueueConfig.closeQueues();
      console.log('✅ 队列系统已关闭');
    }

    // 4. 关闭数据库连接
    if (db && db.close) {
      await db.close();
      console.log('✅ 数据库连接已关闭');
    }

    console.log('✅ 系统已优雅关闭');
    process.exit(0);

  } catch (error) {
    console.error('❌ 优雅关闭过程中发生错误:', error);
    process.exit(1);
  }
}

/**
 * 主启动函数
 */
async function main() {
  console.log('🚀 启动EndoSight-UC异步架构系统...');
  console.log(`📧 环境: ${NODE_ENV}`);
  console.log(`🔌 端口: ${PORT}`);
  console.log('=' .repeat(50));

  try {
    // 检查Node.js版本
    const nodeVersion = process.version;
    const majorVersion = parseInt(nodeVersion.slice(1).split('.')[0]);

    if (majorVersion < 16) {
      console.warn('⚠️ 建议使用Node.js 16或更高版本');
    }

    console.log(`✅ Node.js版本: ${nodeVersion}`);

    // 1. 初始化队列系统
    await initializeQueueSystem();

    // 2. 启动AI推理Worker
    await startAIInferenceWorker();

    // 3. 启动Express服务器
    await startExpressServer();

    // 4. 启动监控和日志
    await startMonitoring();

    console.log('=' .repeat(50));
    console.log('🎉 EndoSight-UC异步架构系统启动完成！');
    console.log('🎯 解决net::ERR_CONNECTION_RESET问题的异步架构已就绪');
    console.log('=' .repeat(50));

    // 设置优雅关闭处理
    process.on('SIGINT', () => gracefulShutdown('SIGINT'));
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));

  } catch (error) {
    console.error('❌ 系统启动失败:', error);
    process.exit(1);
  }
}

// 未捕获异常处理
process.on('uncaughtException', (error) => {
  console.error('❌ 未捕获异常:', error);
  gracefulShutdown('uncaughtException');
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('❌ 未处理的Promise拒绝:', reason);
  gracefulShutdown('unhandledRejection');
});

// 启动系统
if (require.main === module) {
  main();
}

module.exports = {
  main,
  gracefulShutdown,
  initializeQueueSystem,
  startAIInferenceWorker,
  startExpressServer,
  startMonitoring
};